﻿using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace Viettel.VOFFICE.Web.Helpers
{
    /// <summary>
    /// Chống tấn công bằng CSRF cho các request đi qua json 
    /// https://github.com/Haacked/CodeHaacks/blob/master/src/MvcHaack.Ajax.V2/ValidateJsonAntiForgeryTokenAttribute.cs (Nếu update lên mvc4)
    /// Xem thêm trong file js
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public string Salt
        {
            get;
            set;
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            var httpContext = new JsonAntiForgeryHttpContextWrapper(HttpContext.Current);
            AntiForgery.Validate(httpContext, Salt ?? string.Empty);
        }

        /// <summary>
        /// Lấy thông tin từ request nó là ajax request dạng $.get $.set this.model.save
        /// </summary>
        private class JsonAntiForgeryHttpContextWrapper : HttpContextWrapper
        {
            readonly HttpRequestBase _request;
            public JsonAntiForgeryHttpContextWrapper(HttpContext httpContext)
                : base(httpContext)
            {
                _request = new JsonAntiForgeryHttpRequestWrapper(httpContext.Request);
            }

            public override HttpRequestBase Request
            {
                get
                {
                    return _request;
                }
            }
        }

        /// <summary>
        /// Lấy thông tin request nếu nó là form ajax request
        /// </summary>
        private class JsonAntiForgeryHttpRequestWrapper : HttpRequestWrapper
        {
            readonly NameValueCollection _form;

            public JsonAntiForgeryHttpRequestWrapper(HttpRequest request)
                : base(request)
            {
                _form = new NameValueCollection(request.Form);
                if (request.Headers["__RequestVerificationToken"] != null)
                {
                    _form["__RequestVerificationToken"] = request.Headers["__RequestVerificationToken"];
                }
            }

            public override NameValueCollection Form
            {
                get
                {
                    return _form;
                }
            }
        }
    }
}
